<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #list,
        #empty {
            display: none;
        }
    </style>
</head>

<body>
    <input type="text" id="txt">
    <button id="rearch">搜索</button>
    <hr>
    <ul id="list">

    </ul>
    <p id="empty">暂无数据</p>
</body>
<script>
    var txt = document.getElementById('txt');
    var rearch = document.getElementById('rearch');
    var list = document.getElementById('list');
    var empty = document.getElementById('empty');

    var arr = []; //储存历史记录
    var books = localStorage.getItem('books'); //在本地储存中获取books“值伪为数组arr”
    if (books) {
        arr = JSON.parse(books);
        console.log(arr);
        // 判断数组中是否有数据，有的话遍历渲染，没有的话提示“暂无数据”。
        if (arr.length) {
            arr.forEach(function (item, index) {
                console.log(item);
                list.innerHTML += `<li><span>${item}</span>-----<button>删除</button></li>`;
                list.style.display = 'block';
            })
        } else {
            empty.style.display = "block";
        }
    }


    // 点击搜索按钮
    rearch.onclick = function () {
        // 检索数据
        var res = arr.some(function (item) {
            return item == txt.value;
        })

        if (!res) {
            list.innerHTML += `<li><span>${txt.value}</span>-----<button>删除</button></li>`;
            list.style.display = 'block';
            empty.style.display = "none";
            // 更新数据
            arr.push(txt.value);
            localStorage.setItem('books', JSON.stringify(arr));
           
        }
    }


    // 删除历史数据
    var btns = list.getElementsByTagName('button');
    list.onclick = function (e) {
        if (e.target.nodeName == 'BUTTON') {
            list.removeChild(e.target.parentNode);
            // 更新数据
            var i = Array.from(btns).findIndex(function (item) {
                return item == e.target;
            })
            console.log(i);
            arr.splice(i, 1);
            localStorage.setItem('books', JSON.stringify(arr));
            if (arr.length == 0) {
                empty.style.display = "block";
                list.style.display = 'none';
            }
        }
    }

</script>

</html>